package org.wx.ormtest.init;

import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description: 初始化数据
 * @author: wangxun
 * @createDate: 2021/3/2
 * @version: 1.0
 */
@Slf4j
public class InitData implements Runnable{
    private final static String DRIVERCLASS = PropertiesHelper.get("driverClass");
    private final static String URL =  PropertiesHelper.get("url");
    private final static String USERNAME = PropertiesHelper.get("userName");
    private final static String PASSWORD =  PropertiesHelper.get("password");



    @Override
    public void run() {
        long startTime = System.currentTimeMillis();
        log.info("进入初始化方法...{}",startTime);
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            //SPI注册驱动
            Class.forName(DRIVERCLASS);
            // 连接
            connection = DriverManager.getConnection(URL,USERNAME,PASSWORD);
            statement = connection.prepareStatement("insert into orm.t_user(user_name, password) VALUES (?,?)");
            for (int i = 1; i < 1_000_000; i++) {
                statement.setString(1,"java"+i);
                statement.setString(2, UUID.randomUUID().toString());
                statement.addBatch();
                if(i%100_000==0){
                    //每10万提交一次
                    log.info("每10万提交一次,当前执行到:{}次",i);
                    statement.executeBatch();
                }
            }
            statement.executeBatch();
            log.info("{} 执行完毕，总共花费：{}",Thread.currentThread().getName(),(System.currentTimeMillis()-startTime));
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                statement.close();
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        InitData initData = new InitData();
        final ExecutorService es = Executors.newFixedThreadPool(20);
        for (int i = 0; i < 20; i++) {
            es.submit(initData);
        }
    }
}
